package com.qf.api.controller;

import com.qf.api.service.ProductService;
import com.qf.api.service.TenantService;
import com.qf.common.bean.R;
import com.qf.common.dto.ProductDto;
import com.qf.common.model.QfProduct;
import com.qf.common.model.QfTenant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 千锋健哥
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private ProductService productService;

    @PostMapping("/all")
    public R<List> findAll(@RequestBody ProductDto dto) {
        //1. 从请求头中获取token, 如果token为空则无权限查询
        String accessKey = request.getHeader("token");
        if (StringUtils.isEmpty(accessKey)) {
            return R.fail("缺少租户, 无权限查询!");
        }

        //2. 根据token也就是accessKey, 到数据库的租户表中查询是否正确, 如果查不到, 则无权限
        QfTenant tenant = tenantService.findTenantByAccessKey(accessKey);
        if (tenant == null) {
            return R.fail("租户错误, 无权限查询!");
        }

        //3. 根据条件查询产品
        if (dto == null) {
            dto = new ProductDto();
            dto.setTenantId(tenant.getId());
        }

        R<List> result = productService.findAreaAll(dto);
        return result;
    }
}
